﻿using System.Data.SqlClient;
using log4net.Appender;
using log4net.Core;
using Npgsql;

namespace MvcCms.PGAppender
{
    public sealed class MvcCmsPGAppender : IAppender, IOptionHandler
    {
        private string m_connectionString;
        private string m_name;
        public string ConnectionString
        {
            get { return m_connectionString; }
            set { m_connectionString = value; }
        }
        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }

        public void ActivateOptions()
        {

        }

        public void Close()
        {

        }

        public void DoAppend(LoggingEvent loggingEvent)
        {
            using (var conn = new NpgsqlConnection(ConnectionString))
            {
                conn.Open();
                using (var comm = new NpgsqlCommand("insert_to_log", conn))
                {
                    comm.CommandType = System.Data.CommandType.StoredProcedure;
                    comm.Parameters.Add("_log_date", NpgsqlTypes.NpgsqlDbType.Timestamp).Value = loggingEvent.TimeStamp;
                    
                    comm.Parameters.Add("_thread", NpgsqlTypes.NpgsqlDbType.Varchar, 255).Value = loggingEvent.ThreadName;

                    comm.Parameters.Add("_log_level", NpgsqlTypes.NpgsqlDbType.Varchar, 50).Value = loggingEvent.Level.Name;

                    comm.Parameters.Add("_logger", NpgsqlTypes.NpgsqlDbType.Varchar, 255).Value = loggingEvent.LoggerName;

                    comm.Parameters.Add("_message", NpgsqlTypes.NpgsqlDbType.Text).Value = loggingEvent.RenderedMessage;
                    comm.Parameters.Add("_exception", NpgsqlTypes.NpgsqlDbType.Text).Value = loggingEvent.GetExceptionString();
                    comm.ExecuteNonQuery();
                }
            }


        }
    }
}
